<?php
/**
 * Assignment repository
 */
namespace BWL\webshopBundle\Repository;

use Doctrine\ORM\EntityRepository;
use BWL\webshopBundle\Entity\Item;

/**
 * AssignmentRepository
 *
 * Assignment specific methods to locale entity.
 */
class AssignmentRepository extends EntityRepository
{

  /**
   * Find assignments in period
   * @param \DateTime $from
   * @param \DateTime $to
   * @return array
   */
  public function findByPeriod(\DateTime $from, \DateTime $to) {
    $to->modify('+1 day');

    $qb = $this->createQueryBuilder('a')
      ->select('a');
    $qb->leftJoin('a.item', 'c');
    $qb->where('a.date >= ?1');
    $qb->andWhere('a.date < ?2');
    $qb->orderBy('c.name', 'ASC');
    $qb->addOrderBy('a.date', 'ASC');

    $qb->setParameters(array(
      1 => $from,
      2 => $to
    ));

    return $qb->getQuery()->getResult();
  }

  /**
   * Return one Assignment by Component and Date (without time) or null.
   * @param \BWL\webshopBundle\Entity\Item $item
   * @param \DateTime $date
   * @return mixed
   */
  public function findByComponentAndDate(Item $item, \DateTime $date, $leadDays = 0) {
    if ($leadDays <= 0) {
      return $this->findOneBy(array('item' => $item, 'date' => $date));
    }

    $from = clone $date;
    $from->modify('-' . $leadDays . ' days');

    $qb = $this->createQueryBuilder('a')
      ->select('a');
    $qb->where('a.item = ?1');
    $qb->andWhere('a.date >= ?2');
    $qb->andWhere('a.date <= ?3');
    $qb->orderBy('a.date', 'ASC');
    $qb->setMaxResults(1);

    $qb->setParameters(array(
      1 => $item,
      2 => $from,
      3 => $date,
    ));

    return $qb->getQuery()->getOneOrNullResult();
  }

}